# -*- coding: utf-8 -*-
######################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 OpenERP s.a. (<http://openerp.com>).
# Copyright (C) 2013 INIT Tech Co., Ltd (http://init.vn).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
######################################################################

from osv import fields, osv
from tools.translate import _
import pooler
import netsvc
from email.Utils import COMMASPACE
import time
from datetime import date, datetime, timedelta

class init_mail_group(osv.osv):
    _inherit = "mail.group"
    

    def send_mail(self, cr, uid, ids, filtered_users=[], sub="", cc=[]):
        print 'ok nha'
        
        def createReport(cr, uid, report, ids, data, name=False):
            files = []
            for id in ids:
                try:
                    ctx = {
                     'lang': u'en_US',
                     'tz': False, }
                    service = netsvc.LocalService(report)
                    (result, format) = service.create(cr, uid, [id], data, ctx)
                    if not name:
                        report_file = '/tmp/reports' + str(id) + '.pdf'
                    else:
                        report_file = name
                    
                    fp = open(report_file, 'wb+')
                    fp.write(result);
                    fp.close();
                    files += [report_file]    
                except Exception, e:
                    continue        
            return files
        
        pool = self.pool
        result = None
        context = None
        
        smtp = self.pool.get('email.smtpclient')
        smtpserver_id = self.pool.get('email.smtpclient').select(cr, uid, 'massmail')

        if smtpserver_id is False:
            raise Exception, _('Please check the Server Configuration!')
        
        email = []
        subject = ''
        history = {}
        dupplicate_ids = []
        for grp in self.browse(cr, uid, ids):
            if grp.member_ids:
                print 'grp.member_ids' , grp.member_ids
                for seq in grp.seq_ids:
                    for member in grp.member_ids:
                        # if member.partner_id and member.partner_id.address and member.partner_id.address[0].email:
                        if member.email:
                            to = member.email
                            partner = member.prospect
                            
                        subject = seq.template_id.name
                        body = seq.template_id.body
                        reports = []
                        if seq.template_id.report_template:
                            reportname = 'report.' + seq.template_id.report_template.report_name
                            data = {}
                           
                            if seq.template_id.model_id:
                                osv_memory = seq.template_id.model_id.osv_memory
                                if osv_memory:
                                    vals = {}
                                    for condition in seq.template_id.line_ids:
                                        value = condition.value
#                                        if value:
#                                            value = eval(value)
                                        if condition.daily:
                                            value = time.strftime('%Y-%m-%d')
                                        vals.update({condition.field_id.name: value})
                                    obj_id = pool.get(seq.template_id.report_template.model).create(cr, uid, vals)
                                    data['model'] = seq.template_id.report_template.model
                                    data['form'] = vals
                                    
                                    reports = [(reportname, [obj_id], data, seq.template_id.file_name)]
                                else:
                                    reports = [(reportname, [10], {}, seq.template_id.file_name)]                                    
                        attachments = []
                        # attachment from Reports
                        for rpt in reports:
                            new_uid = grp.user_id and grp.user_id.id or uid
                            if len(rpt) == 4:
                                rpt_file = createReport(cr, new_uid, rpt[0], rpt[1], rpt[2], rpt[3])
                            elif len(rpt) == 3:
                                rpt_file = createReport(cr, new_uid, rpt[0], rpt[1], rpt[2])
                            elif len(rpt) == 2:
                                rpt_file = createReport(cr, new_uid, rpt[0], rpt[1])
                            attachments += rpt_file
                        
                        smtpserver = self.pool.get('email.smtpclient').browse(cr, uid, smtpserver_id, context=False)
                        email = COMMASPACE.join([to])
                        
                        body = (body or smtpserver.body) or ''
                        body = body and body.replace('__partner__', partner or '')

                        current_time = time.strftime('%Y-%m-%d')


                        if seq.state == 'draft' and seq.next_call and seq.next_call < current_time:
                            self.pool.get('mail.sequence').write(cr, uid, [seq.id], {'state':'pending'})
                        if seq.state == 'draft' and seq.next_call and seq.next_call <= current_time:
                            if seq.mail_type != 'not_interested':
                                state = self.pool.get('email.smtpclient').send_email(cr, uid, smtpserver_id,
                                            email, subject.encode('utf-8'), body.encode('utf-8'), attachments, [], [])
                                cr.commit()

                                if not state:
                                    raise Exception, _('Verification failed, Please check the Server Configuration!')

                                self.pool.get('mail.sequence').write(cr, uid, [seq.id], {'state':'sent'})       
                                if seq.id not in dupplicate_ids:
                                    self.pool.get('mail.sequence').copy(cr, uid, seq.id, {
                                                                                          'next_call': datetime.strptime(seq.next_call, "%Y-%m-%d") + timedelta(days=1),
                                                                                          })
                                    dupplicate_ids.append(seq.id)

                            if seq.mail_type == 'not_interested' and member.not_interested == True:
                                state = self.pool.get('email.smtpclient').send_email(cr, uid, smtpserver_id,
                                            email, subject.encode('utf-8'), body.encode('utf-8'), attachments, [], [])
                                cr.commit()

                                if not state:
                                    raise Exception, _('Verification failed, Please check the Server Configuration!')
                                self.pool.get('mail.sequence').write(cr, uid, [seq.id], {'state':'sent'})
                                if seq.id not in dupplicate_ids:
                                    self.pool.get('mail.sequence').copy(cr, uid, seq.id, {
                                                                                          'next_call': datetime.strptime(seq.next_call, "%Y-%m-%d") + timedelta(days=1),
                                                                                          })
                                    dupplicate_ids.append(seq.id)
                                
                                # self.pool.get('mail.sequence').unlink(cr, uid, seq.id, context=context)  
#                                  
                    to = ''        
        return True


init_mail_group()

class mail_sequence(osv.osv):
    _inherit = "mail.sequence"
    _defaults = {
        'state': lambda *a: 'draft',
        'mail_type': lambda *a: 'interested',
    }
mail_sequence()

class mail_group_member(osv.osv):
    _inherit = "mail.group.member"
    _defaults = {
        'not_interested': lambda *a: True,
    }
mail_group_member()
